import datetime
import uuid

from sqlalchemy import insert, select, update, delete

from apps.goods.goods_form import SearchGoodsForm
from config.const import error_code
from apps.goods import goods_blueprint
from flask import jsonify, request

from database.user_model import users, DBCustomQuery, goods
from forword.decorators.token_decorator import token_require



# user_list
@goods_blueprint.route('/goods_list')
@token_require
def get_goods_list():
    search_form = SearchGoodsForm(**request.args)
    sql_model = DBCustomQuery(goods, ['deleted_at']).filter_deleted()

    if search_form.goods_number:
        sql_model = sql_model.where(goods.c.goods_number == search_form.goods_number)

    # if search_form.goods_cn_name:
    #     sql_model = sql_model.where(users.c.goods_cn_name.like(r'%{}%'.format(search_form.goods_cn_name)))
    #
    # if search_form.goods_en_name:
    #     sql_model = sql_model.where(users.c.goods_en_name.like(r'%{}%'.format(search_form.goods_en_name)))

    goods_list = list(
        map(
            lambda x: dict(x),
            sql_model.paginate(search_form.page_num, search_form.page_size).fetchall()
        )
    )

    count = sql_model.count().scalar()
    return jsonify({"error_code": error_code.CODE_SUCCESS, "data": {"goods_list": goods_list, "count": count}})

# @goods_route.route('/user_update', methods=["PATCH"])
# @admin_token_require
# def update_user():
#     update_form = UpdateUserForm(**request.json)
#
#     update_dict = dict(filter(lambda up: up[1], update_form.dict().items()))
#     update_dict["roles"] = ",".join(update_dict["roles"])
#     update_dict["password"] = encrypt_util.hash(update_dict["password"])
#     del update_dict["id"]
#     # result.rowcount
#     upt = update(users).where(users.c.id == update_form.id).values(**update_dict)
#     db_session().execute(upt)
#     db_session().commit()
#     print(update_form)
#
#     return jsonify({"error_code": error_code.CODE_SUCCESS, "msg": "更新成功"})
#
#
# @goods_route.route('/', methods=["DELETE"])
# @admin_token_require
# def del_user():
#     del_user_id = request.args.get("id")
#
#     upt = update(users).where(users.c.id == del_user_id).values(**{"deleted_at": datetime.datetime.now()})
#     db_session().execute(upt)
#     db_session().commit()
#
#     return jsonify({"error_code": error_code.CODE_SUCCESS, "msg": "删除成功"})
